package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 方法说明：
     *
     * @MethodName 合并采购需求,将采购的需求合并到采购单上
     * @Description    
     * @Author chenCheng
     * @EMAIL <2277411582@qq.com>
     * @Date 2022/9/29 17:37  
     * @修改人及日期：
     * @修改说明：
     */
    @Override
    public void mergePurchase(MergeVo mergeVo) {

        // 1.获取需要合并的采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            // 我们新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            // 新建一个采购单
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());

            this.save(purchaseEntity);
           // 保存后拿到其id
            purchaseId = purchaseEntity.getId();
        }
        // 走到这里这个采购单就是有值的,我们将需要合并的采购需求设置给这个采购单
        // 得到要合并的项的id(就是我们得采购需求的id)
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {

            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 设置id
            detailEntity.setId(i);
            // 设置采购单的id
            detailEntity.setPurchaseId(finalPurchaseId);
            // 设置状态
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        // 然后我们更新这些采购需求
        detailService.updateBatchById(collect);


        // 更新这个采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 方法说明：
     *
     * @MethodName 查寻没有被领取的采购单
     * @Description
     * @Author chenCheng
     * @EMAIL <2277411582@qq.com>
     * @Date 2022/9/29 18:13
     * @修改人及日期：
     * @修改说明：
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",WareConstant.PurchaseStatusEnum.CREATED.getCode()).or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );
        return new PageUtils(page);
    }

    /**
     * 方法说明：
     *
     * @MethodName 采购人员领取采购单
     * @Description    
     * @Author chenCheng
     * @EMAIL <2277411582@qq.com>
     * @Date 2022/9/29 18:24  
     * @修改人及日期：
     * @修改说明：
     */
    @Override
    public void received(List<Long> ids) {
        // 传过来的时采购单的id集合,我们需要确定当前采购单是没有被领取过的
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            // 获取当每一个采购单的信息
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            // 我们只要未分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            //把采购单的状态设置为已经被采购人员接收
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

//        for (PurchaseEntity item : collect) {
//            //把采购单的状态设置为已经被采购人员接收
//            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
//            item.setUpdateTime(new Date());
//        }
        // 更新采购单信息
        this.updateBatchById(collect);


        // 3.更新完采购单的信息,我们需要更新采购需求
        collect.forEach((item)->{
            // 获取这个采购单下的所有的采购需求
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities  = entities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });


    }

    /**
     * 方法说明：
     *
     * @MethodName 完成采购
     * @Description
     * @Author chenCheng
     * @EMAIL <2277411582@qq.com>
     * @Date 2022/9/29 18:44
     * @修改人及日期：
     * @修改说明：
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 获取采购单的id
        Long id = doneVo.getId();
        // 获取到采购需求
        // 加一个同步的标识,来表示当前采购需求有没有完成
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        // 这个容器里的是已经完成的采购需求,需要更新
        List<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemDoneVo item : items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 如果当前采购需求采购失败,设置失败信息
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                // 设置flag为false
                flag = false;
                // 设置其状态为采购失败
                detailEntity.setStatus(item.getStatus());
                // todo 这个采购失败的一个信息,我们现在库里没存这个字段
                String reason = item.getReason();
            }else {
                // 设置采购需求已完成
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                // 获取到这个采购需求的详情信息
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                if(entity != null){
                    // 采购成功将数量添加到仓库中
                    wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
                }
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        // 更新这个采购需求的状态,
        detailService.updateBatchById(updates);


        // 到这个我们判断,这个采购需求是不是全部都采购成功了,如果有采购失败的,我们需要设置状态为失败
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}